import {
  BaseFormDight,
  BaseFormSelect,
  BaseModalForm,
  ProFormDatePicker,
  ProFormDependency,
  ProFormInstance,
  ProFormSelect
} from '@/components/base/BaseForm';
import { ModalFC } from '@/components/base/BaseModal';
import { StockModel } from '@/pages/radar/data';
import useUserStore from '@/store/user';
import { isEmpty } from '@/utils/is';
import { Col, Row } from 'antd';
import moment from 'moment';
import { useRef } from 'react';
import { getList as getKeyPartsModelInfo } from '../../KeyPartsModelInfo/api';
import { addStockInfo, editStockInfo, getList as getStorageHomeList } from '../api';

const StockInfoModal: ModalFC<{ areaId?: string; data: StockModel; isStorageHome?: boolean }> = (
  props
) => {
  const { areaId, data = {} as StockModel, isStorageHome = true, onSuccess, ...anyProps } = props;
  const { id } = data;
  const isadd = isEmpty(id);
  const {
    userinfo: { area }
  } = useUserStore();
  const formRef = useRef<ProFormInstance<StockModel>>();
  return (
    <BaseModalForm<StockModel>
      title='库存信息'
      formRef={formRef}
      labelCol={{ style: { width: 90 } }}
      width={640}
      initialValues={{ ...data }}
      {...anyProps}
      onFinish={async (values) => {
        if (isStorageHome && areaId) {
          values.areaId = areaId;
        }
        const { ok } = await (isadd ? addStockInfo : editStockInfo)({ ...data, ...values });
        ok && onSuccess && onSuccess();
        return ok;
      }}
    >
      {isStorageHome ? (
        <BaseFormSelect
          label='关重件型号'
          request={getKeyPartsModelInfo}
          placeholder='请选择关重件型号'
          name='keyPartsModelId'
          readonly={!isadd}
          fieldProps={{
            defaultSelectedOptions: [
              { typeName: '', name: data.keyPartsModelName, id: data.keyPartsModelId }
            ],
            fieldNames: { label: (data: any) => data.typeName + data.name, value: 'id' }
          }}
          rules={[{ required: true, message: '请选择关重件型号' }]}
        />
      ) : (
        <>
          {isadd && (
            <ProFormSelect
              label='区域'
              name='areaId'
              placeholder='请选择库房所属区域'
              options={area.map((i) => ({ label: i.areaName, value: i.areaId }))}
              fieldProps={{
                onChange() {
                  formRef.current?.setFieldsValue({ storageHomeId: undefined });
                }
              }}
            />
          )}
          <ProFormDependency name={['areaId']}>
            {({ areaId }) => (
              <BaseFormSelect
                label='库房'
                request={getStorageHomeList}
                params={{ areaId }}
                placeholder='请选择库房'
                name='storageHomeId'
                readonly={!isadd}
                fieldProps={{
                  defaultSelectedOptions: [{ name: data.storageHomeName, id: data.storageHomeId }],
                  fieldNames: { label: 'name', value: 'id' }
                }}
                rules={[{ required: true, message: '请选择库房' }]}
              />
            )}
          </ProFormDependency>
        </>
      )}
      <Row gutter={8}>
        <Col span={12}>
          <BaseFormDight
            fieldProps={{ step: 1, min: 0, precision: 0 }}
            label='库存'
            name='storageNum'
            placeholder='请输入库存'
            rules={[{ required: true, message: '请输入库存' }]}
          />
        </Col>

        <Col span={12}>
          <ProFormDatePicker
            fieldProps={{
              style: { width: '100%' },
              onChange() {
                formRef.current?.validateFields(['addDate']);
              },
              disabledDate: (current) => {
                return current && current > moment().endOf('day');
              }
            }}
            label='生产日期'
            name='manufactureDate'
            placeholder='请选择生产日期'
            rules={[
              { required: true, message: '请选择生产日期' },
              (form) => {
                return {
                  validator: (_, value) => {
                    const addDate = form.getFieldValue('addDate');
                    if (moment(value).format('YYYY-MM-DD') > moment(addDate).format('YYYY-MM-DD')) {
                      return Promise.reject(new Error('生产日期不能在入库日期之后'));
                    }
                    return Promise.resolve();
                  }
                };
              }
            ]}
          />
        </Col>
        <Col span={12}>
          <ProFormDatePicker
            fieldProps={{
              style: { width: '100%' },
              onChange() {
                formRef.current?.validateFields(['manufactureDate']);
              },
              disabledDate: (current) => {
                const manu = formRef.current?.getFieldValue('manufactureDate');
                return current && current <= moment(manu).startOf('day');
              }
            }}
            label='入库日期'
            name='addDate'
            placeholder='请选择入库日期'
            rules={[
              { required: true, message: '请选择入库日期' },
              (form) => {
                return {
                  validator: (_, value) => {
                    const manu = form.getFieldValue('manufactureDate');
                    if (moment(value).format('YYYY-MM-DD') < moment(manu).format('YYYY-MM-DD')) {
                      return Promise.reject(new Error('入库日期不能在生产日期之前'));
                    }
                    return Promise.resolve();
                  }
                };
              }
            ]}
          />
        </Col>
        <Col span={12}>
          <BaseFormDight
            label='有效期'
            name='validityDate'
            placeholder='请输入有效期'
            required
            rules={[{ required: true, message: '请输入有效期' }]}
            fieldProps={{ step: 1, min: 0 }}
            addonAfter='月'
          />
        </Col>
      </Row>
    </BaseModalForm>
  );
};

export default StockInfoModal;
